<script setup lang='ts'>
import type { OptionsType, PlusColumn } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useFailExport, useGetCascadeData, useGetVerifyFailPage } from '@fl/api/elevator-api/verify'
import { SearchForm, SearchTable } from '@fl/components'
import { treeFindLabel } from '@fl/utils/tree'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash-es'

import { hasPermi } from '@fl/utils/has-permi'
import failEdit from './components/fail-edit.vue'
import VerifyResult from './components/verify-result.vue'
import { AUTH_RESULT, AUTH_RESULT_OPTIONS, VERIFY_STATUS, VERIFY_STATUS_OPTIONS } from './constant'

defineOptions({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'identity-verify-fail-list',
})

const showVerifyResult = ref<boolean>(false)
const verifyResultData = ref<any>()

const initialState = {} as any
const state = ref(cloneDeep(initialState))
const searchConditions = ref(cloneDeep(initialState))
const editId = ref<string>('')
const editVisible = ref<boolean>(false)
const projectName = ref<string>('')
const positionInfo = ref<any>() // 经纬度信息

const tablePage = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

const getAreaOptionsParams = computed(() => ({
    targetLabel: 'area',
}))
const getStreetOptionsParams = computed(() => ({
    areaCode: state.value.areaCode,
    targetLabel: 'street',
}))
const getCommunityOptionsParams = computed(() => ({
    streetCode: state.value.streetCode,
    targetLabel: 'community',
}))
const getProjectOptionsParams = computed(() => ({
    communityCode: state.value.communityCode,
    targetLabel: 'project',
    projectName: projectName.value,
}))
const getBuildingOptionsParams = computed(() => ({
    projectId: state.value.projectId,
    targetLabel: 'building',
}))
const getUnitOptionsParams = computed(() => ({
    buildingId:buildingOptions.value && state.value.building
  ? (buildingOptions.value.find(item => item.label === state.value.building)?.buildingId ?? '')
  : '',
    building: state.value.building,
    targetLabel: 'unit',
}))
const getVerifyFailPageParams = computed(() => ({
    ...searchConditions.value,
    endTime: searchConditions.value.submitTimeRange?.[1],
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    startTime: searchConditions.value.submitTimeRange?.[0],
}))

const { data: areaOptions } = useGetCascadeData(getAreaOptionsParams)
const { data: streetOptions } = useGetCascadeData(getStreetOptionsParams, 'areaCode')
const { data: communityOptions } = useGetCascadeData(getCommunityOptionsParams, 'streetCode')
// const { data: projectOptions } = useGetCascadeData(getProjectOptionsParams, 'communityCode')
// const { data: buildingOptions } = useGetCascadeData(getBuildingOptionsParams, 'projectId')
const { data: projectOptions, isLoading: projectLoading } = useGetCascadeData(
    getProjectOptionsParams,
    'projectName',
)
const { data: buildingOptions } = useGetCascadeData(
    getBuildingOptionsParams,
    'projectId',
)
const { data: unitOptions } = useGetCascadeData(getUnitOptionsParams, 'building')
const { data: verifyFailPageData, isLoading: isGetVerifyFailPageLoading, total: verifyFailTotal } = useGetVerifyFailPage(getVerifyFailPageParams)

// #region Form
const isFormLoading = computed(() => false)

// 导出
const exportParams = computed(() => ({
    // ...searchConditions.value,
    areaCode: searchConditions.value.areaCode,
    streetCode: searchConditions.value.streetCode,
    communityCode: searchConditions.value.communityCode,
    projectId: searchConditions.value.projectId,
    building: searchConditions.value.building,
    unit: searchConditions.value.unit,
    ownerName: searchConditions.value.ownerName,
    status: searchConditions.value.status,
    auth: searchConditions.value.auth,
    endTime: searchConditions.value.submitTimeRange?.[1],
    startTime: searchConditions.value.submitTimeRange?.[0],
}))
const { isPending, mutateAsync } = useFailExport(exportParams)
async function exportData() {
    const res = await mutateAsync()
    if (res) {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '所在区',
        options: areaOptions as OptionsType,
        prop: 'areaCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '街道',
        options: streetOptions as OptionsType,
        prop: 'streetCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '社区',
        options: communityOptions as OptionsType,
        prop: 'communityCode',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '小区',
        options: projectOptions as OptionsType,
        prop: 'projectId',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '栋',
        options: buildingOptions as OptionsType,
        prop: 'building',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        fieldProps: {
            filterable: true,
        },
        label: '单元',
        options: unitOptions as OptionsType,
        prop: 'unit',
        valueType: 'select',
    },
    {
        colProps: {
            span: 6,
        },
        label: '业主信息',
        prop: 'ownerName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '编号',
        prop: 'applyNo',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 8,
        },
        label: '身份初步对比结果',
        labelWidth: 140,
        options: AUTH_RESULT_OPTIONS,
        prop: 'auth',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        label: '身份核实状态',
        options: VERIFY_STATUS_OPTIONS,
        prop: 'status',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            'endPlaceholder': '请选择结束时间',
            'startPlaceholder': '请选择开始时间',
            'type': 'datetimerange',
            'valueFormat': 'YYYY-MM-DD HH:mm:ss',
            'disabled-date': (time: Date) => {
                return dayjs(time).isAfter(dayjs(new Date()).format('YYYY-MM-DD 23:59:59'))
            },
        },
        label: '提交时间',
        prop: 'submitTimeRange',
        valueType: 'date-picker',
    },
]

function submit() {
    searchConditions.value = cloneDeep(state.value)
    resetTablePage()
}

function reset() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    resetTablePage()
}

function resetTablePage() {
    tablePage.currentPage = 1
    tablePage.pageSize = 10
}

function projectSearch(keyword) {
    projectName.value = keyword
}

watch(() => state.value.areaCode, () => {
    const { building, communityCode, projectId, streetCode, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.streetCode, () => {
    const { building, communityCode, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.communityCode, () => {
    const { building, projectId, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.projectId, () => {
    const { building, unit, ...data } = state.value
    state.value = cloneDeep(data)
})

watch(() => state.value.building, () => {
    const { unit, ...data } = state.value
    state.value = cloneDeep(data)
})
// #endregion

// #region Table
const isTableLoading = computed(() => isGetVerifyFailPageLoading.value)
const tableData = ref<any[]>([])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { field: 'applyNo', title: '编号', width: 240 },
        { field: 'areaName', title: '所在区', width: 100 },
        { field: 'streetName', title: '街道', width: 100 },
        { field: 'communityName', title: '社区', width: 100 },
        { field: 'projectName', title: '小区', width: 100 },
        { field: 'buildingAndUnit', slots: { default: 'building_and_unit' }, title: '栋-单元', width: 100 },
        { field: 'natureNo', title: '自然栋编号', width: 100 },
        { field: 'applicantMobile', title: '上报人账号', width: 120 },
        { field: 'ownerName', title: '业主姓名', width: 80 },
        { field: 'ownerIdCard', title: '业主身份证号', width: 200 },
        { field: 'houseAddr', title: '详细地址', width: 200 },
        { field: 'auth', slots: { default: 'auth' }, title: '身份初步对比结果', width: 80 },
        { field: 'status', slots: { default: 'status' }, title: '身份核实状态', width: 110 },
        { field: 'createTime', title: '提交时间', width: 170 },
        { fixed: 'right', slots: { default: 'operation' }, title: '操作', width: 140 },
    ],
})
// #endregion

// #region UI Listener
// function onExportBtnClick() {

// }

function onVerifyBtnClick(row: any) {
    verifyResultData.value = row
    showVerifyResult.value = true
    positionInfo.value = {
        longitude: Number(row.longitude),
        latitude: Number(row.latitude),
    }
}

function onDetailBtnClick(row: any) {
    verifyResultData.value = row
    showVerifyResult.value = true
    positionInfo.value = {
        longitude: Number(row.longitude),
        latitude: Number(row.latitude),
    }
}

function onUpdateBtnClick(row: any) {
    editId.value = String(row.id)
    editVisible.value = true
    verifyResultData.value = row
    console.log('修改', editId.value)
}
// #endregion

watchEffect(() => {
    tableData.value = cloneDeep(verifyFailPageData.value)
    tablePage.total = verifyFailTotal.value
})
</script>

<template>
    <el-card mb-20
             shadow="never"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    v-model="state"
                    :columns="columns"
                    submit-text="查询"
                    :row-props="{ gutter: 40 }"
                    @submit="submit"
                    @reset="reset"
        >
            <template #plus-field-projectId>
                <el-select v-model="state.projectId"
                           filterable
                           remote
                           reserve-keyword
                           placeholder="直接搜小区,无需选区域"
                           remote-show-suffix
                           :remote-method="projectSearch"
                           :loading="projectLoading"
                >
                    <el-option v-for="item in projectOptions"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>
        </SearchForm>
    </el-card>

    <el-card shadow="never">
        <SearchTable v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :loading="isTableLoading"
                     :data="tableData"
        >
            <template #toolbar_buttons>
                <div class="mb-12 flex w-full justify-between">
                    <div>
                        <el-button type="primary"
                                   :loading="isPending"
                                   @click="exportData"
                        >
                            <div class="i-iconamoon:upload size-16" />
                            导出
                        </el-button>
                    </div>
                </div>
            </template>

            <template #building_and_unit="{ row }">
                <span>{{ `${row.building}${row.unit === '无' ? '' : `-${row.unit}`}` }}</span>
            </template>

            <template #auth="{ row }">
                <span>{{ treeFindLabel({ targetValue: row.auth, treeData: AUTH_RESULT_OPTIONS }) }}</span>
            </template>

            <template #status="{ row }">
                <!-- 身份初步比对结果=不在清册范围内时，身份核实状态应该显示为/ -->
                <span v-if="row.auth === AUTH_RESULT.ERROR">/</span>

                <span v-else>{{ treeFindLabel({ targetValue: row.status, treeData: VERIFY_STATUS_OPTIONS }) }}</span>
            </template>

            <template #operation="{ row }">
                <el-button v-if="hasPermi('身份失败-修改') && row.auth === AUTH_RESULT.ERROR"
                           class="!p-4"
                           text
                           type="primary"
                           @click="onUpdateBtnClick(row)"
                >
                    修改
                </el-button>

                <el-button v-if="row.status === VERIFY_STATUS.WAITING_FOR_VERIFY && row.auth !== AUTH_RESULT.ERROR && hasPermi('身份失败-审核')"
                           class="!p-4"
                           text
                           type="primary"
                           @click="onVerifyBtnClick(row)"
                >
                    核实结果
                </el-button>

                <el-button v-else
                           class="!p-4"
                           text
                           @click="onDetailBtnClick(row)"
                >
                    详情
                </el-button>
            </template>
        </SearchTable>
    </el-card>

    <VerifyResult v-model:visible="showVerifyResult"
                  v-model:position="positionInfo"
                  :data="verifyResultData"
    />

    <failEdit v-model:visible="editVisible"
              v-model:id="editId"
              :data="verifyResultData"
    />
</template>
